#!/usr/bin/bash
function helpMsg() {
	nextMsg="$1"
	echo "Usage: $(basename $0) <command>"
	echo "Available commands: "
	echo "° diff - creates a diff file (using svn diff) to compare different branches"
	echo "° patch - applies the previously created diff file"
	if test "x$nextMsg" != "x"; then
		echo -e "\n$nextMsg"
	fi
	echo ""
	exit 1
}

function doPatch() {
	if test "x$1" == "x" || ! [ -r "$1" ]; then
		helpMSG="Arguments for patch: <diff file> [optional arguments for patch]"
		helpMsg "$helpMSG"
	fi
	FILE="$1"
	shift
	patch -p0 --no-backup-if-mismatch -l -E --global-reject-file=rejectedDiff.rej -i "$FILE" $@
}

function doDiff() {
      REV1=$1
      REV2=$2
      FILE="$3"
      if test "x$1" == "x" || test "x$2" == "x" || test "x$3" == "x"; then
	helpMSG="Arguments for diff: <first revision> <second revision> <diff file> [optional arguments for svn diff]
Revision number format can either be r1234 or 1234"
	helpMsg "$helpMSG"
      fi
      shift; shift; shift
      #Sostituzione "r1234" con "1234" in modo da facilitare il cut&paste da svn log
      REV1="$( echo $REV1 | sed "s/r//g")"
      REV2="$( echo $REV2 | sed "s/r//g")"
      svn diff -r $REV1:$REV2 --diff-cmd=diff -x -uw $@ > "$FILE" 
}

CMD=$1

if test "x$1" == "x"; then 
	helpMsg
fi
shift
case $CMD in
	"diff")
	doDiff $@
	;;
	"patch")
	doPatch $@
	;;
	*)
	helpMsg
	;;
esac
